package com.ccx.web.front;

import com.ccx.model.EbProduct;
import com.ccx.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private ProductService productService;

    @RequestMapping("/add")
    public String addCart(HttpServletRequest request, Integer epId){
        //1.调用service的根据id查询商品的方法
        EbProduct ebProduct = productService.selectOne(epId);
        //2.获取购物车（session）
        HttpSession session = request.getSession();
        //3.1 获取购物车中的集合
        List<EbProduct> car = (List) session.getAttribute("car");
        //3.2 集合不存在
        if(car==null) {
            car = new ArrayList<EbProduct>(20);
        }
        boolean flag = false;
        for(int i=0;i<car.size();i++){
            EbProduct carProduct = car.get(i);
            if(carProduct.getEpId().equals(ebProduct.getEpId())){
                //此商品已经存在在购物车中了，只要修改改商品的数量 +1
                carProduct.setCount(carProduct.getCount()+1);
                flag=true;
                break;
            }
        }
        //商品不存在在购物车中
        if(!flag){
            car.add(ebProduct);
        }
        //3.3将集合放入购物车
        session.setAttribute("car",car);//key-value

        //使用重定向
        return "redirect:shopping";
    }

    @RequestMapping("/shopping")
    public String showCart(){
        return "shopping";
    }



    @RequestMapping("/delete")
    public String deleteCart(HttpSession  request){
        request.removeAttribute("car");//移除session
        request.invalidate();//清除所有的session，使当前 session 完全失效

        //使用重定向
        return "shopping-result";
    }

}
